// index.js
// 获取应用实例
const app = getApp()

const{connect}=require('../../utils/mqtt')

const mqttHost='mqtts.heclouds.com' //mqtt服务器域名
const mqttPort = 1883 //mqtt服务器端口

const deviceSubTopic = '$sys/5RRfWDSPQr/lora_0/thing/property/get' //设备订阅topic（即小程序发布命令的Topic）
const devicePubTopic = '$sys/5RRfWDSPQr/lora_0/thing/property/get_reply' //设备发布topic（即小程序订阅数据的Topic）

const mpSubTopic = devicePubTopic
const mpPubTopic = deviceSubTopic

const  mqtt_user = "5RRfWDSPQr" // 用户名
const  mqtt_password = "version=2018-10-31&res=products%2F5RRfWDSPQr%2Fdevices%2Flora_0&et=1742554048&method=md5&sign=CJh581XeSEC4PWuXawFNYA%3D%3D"// 密码
const  TM_DEVICE_NAME = "lora_0"

Page({
  data: {
    ti_wen:0,
    shuai_dao:0,
    heart:0
  },

  onLedChange(event){
    const that = this
    console.log(event.detail.value);
    const sw = event.detail.value
    this.setData({Led:sw})

    if(sw){
      that.data.client.publish(mpPubTopic,JSON.stringify({
        target:"LED",
        value:1
      }),function(err){
        if(!err){
          console.log('成功下发指令-开灯')
        }
      })
    }else{
      that.data.client.publish(mpPubTopic,JSON.stringify({
        target:"LED",
        value:0
      }),function(err){
        if(!err){
          console.log('成功下发指令-关灯')
        }
      })
    }
  },
  points:function(e) {
    var that = this
    wx.request({
      url: 'http://iot-api.heclouds.com/thingmodel/query-device-property-detail',
      method: 'POST',
      header: {

        "Authorization": 'version=2018-10-31&res=products%2F5RRfWDSPQr%2Fdevices%2Flora_0&et=1742554048&method=md5&sign=CJh581XeSEC4PWuXawFNYA%3D%3D'
      },
      data: {
        "product_id": "5RRfWDSPQr",
        "device_name": "lora_0",
        "params": ["heart","shuai_dao","ti_wen" ]
      },
      success: function(res) {
        // 请求成功后的处理逻辑
        console.log('请求成功', res.data),
        //如果在 res.data数据中没有指定的键值对就赋值为0，否者把res.data.switch_light_colortemp的值赋值给Ligh
        //
        
        that.setData({
          heart: res.data && res.data.data && res.data.data.heart !== null ? res.data.data.heart : 0,
          shuai_dao: res.data && res.data.data && res.data.data.shuai_dao !== null ? res.data.data.shuai_dao : 0,
          ti_wen: res.data && res.data.data && res.data.data.ti_wen !== null ? res.data.data.ti_wen : 0
        })
          
        
      },
      fail: function(err) {
        // 请求失败的处理逻辑
        console.error('请求失败', err);
      }
    });
    
  },
  startPeriodicUpdate: function() {
    // 每隔一段时间（例如每5分钟）执行一次points函数
    this.intervalId = setInterval(() => {
      this.points();
    }, 1000); // 1秒
  },

  stopPeriodicUpdate: function() {
    clearInterval(this.intervalId); // 清除循环调用
  }

  
})
